#include <stdio.h>
#include <stdlib.h>

typedef struct Matrix
{
    int rows;
    int cols;
    int **data;
}Matrix;

//动态分配矩阵内存
Matrix* createMatrix(int rows, int cols)
{
    Matrix *matrix = (Matrix*)malloc(sizeof(Matrix));//分配结构体Matrix本身的内存
    if (matrix == NULL) 
    {
        printf("内存分配失败！\n");
        return NULL;
    }
    
    matrix->rows = rows;
    matrix->cols = cols;

    //分配行指针
    matrix->data = (int **)malloc(rows * sizeof(int *));
    if(matrix->data == NULL)
    {
        free(matrix);
        printf("内存分配失败！\n");
        return NULL;
    }

    for (int i = 0; i < rows; i++) 
    {
        //为每一列分配空间
        matrix->data[i] = (int*)malloc(cols * sizeof(int));
        if (matrix->data[i] == NULL) 
        {
            // 如果分配失败，释放之前分配的内存
            for (int j = 0; j < i; j++) 
                free(matrix->data[j]);
            
            free(matrix->data);
            free(matrix);
            printf("内存分配失败！\n");
            return NULL;
        }
    }

    return matrix;
}

//输入矩阵
void inputMatrix(Matrix* mat)
{
    if(!mat)
    {
        printf("矩阵不存在！\n");
        return;
    }

    printf("请输入矩阵元素：\n");
    for(int i = 0; i < mat->rows; i++)
    {
        for(int j = 0; j < mat->cols; j++)
        {
            scanf("%d",&mat->data[i][j]);
        }
    }
}

//打印矩阵
void printMatrix(Matrix* mat)
{
    if(!mat)
    {
        printf("矩阵不存在！\n");
        return;
    }

    printf("矩阵%d x %d\n",mat->rows,mat->cols);
    for(int i = 0; i < mat->rows; i++)
    {
        for(int j = 0; j < mat->cols; j++)
        {
            printf("%d ",mat->data[i][j]);
        }
        printf("\n");
    }
}

//释放内存
void freeMatrix(Matrix* mat)
{
    if(!mat)  
        return;
    
    for(int i = 0; i < mat->rows; i++)
        free(mat->data[i]);

    free(mat->data);
    free(mat);
}

Matrix* addMatrices(Matrix* a, Matrix* b)
{
    if(a == NULL || b == NULL)
        return NULL;
    
    if(a->rows != b->rows || a->cols != b->cols)
    {
        printf("矩阵行列不等无法相加！\n");
        return NULL;
    }
    Matrix *c = createMatrix(a->rows,a->cols);
    if(!c)
        return NULL;
    
    for(int i = 0; i < a->rows; i++)
    {
        for(int j = 0; j < a->cols; j++)
        {
            c->data[i][j] = a->data[i][j] + b->data[i][j];
        }
    }

    return c;
}

int main(int argc, char const *argv[])
{
    int m,n;

    printf("请输入矩阵1的行和列：\n");
    scanf("%d %d",&m,&n);
    Matrix *mat1 = createMatrix(m,n);
    inputMatrix(mat1);
    printMatrix(mat1);

    printf("请输入矩阵2的行和列：\n");
    scanf("%d %d",&m,&n);
    Matrix *mat2 = createMatrix(m,n);
    inputMatrix(mat2);
    printMatrix(mat2);

    Matrix *mat = addMatrices(mat1,mat2);
    if(mat)
    {
        printMatrix(mat);
        freeMatrix(mat);
    }

    freeMatrix(mat1);
    freeMatrix(mat2);

    return 0;
}
